package com.dq.netty;

import com.dq.common.LoginMessage;
import com.dq.common.Message;
import com.dq.common.MessageType;
import com.dq.service.UserService;

import io.netty.channel.*;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @Author: Dang Qi
 * @Date: 2021/5/10 15:12
 * @Description:
 * 1. 我们自定义一个Handler 需要继续netty 规定好的某个HandlerAdapter(规范)
 * 2. 这时我们自定义一个Handler , 才能称为一个handler
 */

public class MessageHandler extends SimpleChannelInboundHandler<Message>{

    public static UserService userService= new UserService();
    public static Map<String, ChannelHandlerContext> ctxMap =
            new ConcurrentHashMap<>();
    public static Map<ChannelHandlerContext,String> ctxToQQ =
            new ConcurrentHashMap<>();
    //读取数据实际(这里我们可以读取客户端发送的消息)
    /**
     * 1. ChannelHandlerContext ctx:上下文对象, 含有 管道pipeline , 通道channel, 地址
     * 2. Object msg: 就是客户端发送的数据 默认Object
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        //请求登录
        if(msg.getMesType()==MessageType.message_want_login){
            System.out.println(msg.getSender()+"请求登录");
            LoginMessage loginMessage = (LoginMessage) msg;
            Message m = new Message();
            //登录成功
            if(userService.queryLoginCheck(loginMessage.getSender(), loginMessage.getPasswd())){
                m.setMesType(MessageType.message_succeed);
                add(msg.getSender(), ctx);

            }
            //登录失败
            else {
                m.setMesType(MessageType.message_login_fail);
                ctx.close();
            }
        }
        //普通消息转发
        else if(msg.getMesType() == MessageType.message_comm_mes){
            ChannelHandlerContext targetCtx = ctxMap.get(msg.getReceiver());
            System.out.println("From:"+msg.getSender()+", Message:"+msg.getMessage());
            targetCtx.writeAndFlush(msg.getMessage());
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        remove(ctx);
        String qq = ctxToQQ.get(ctx);
        if(qq!=null){
            System.out.println(qq + "离线了");
        }
    }

    public void add(String qq, ChannelHandlerContext ctx){
        ctxMap.put(qq, ctx);
        ctxToQQ.put(ctx, qq);
    }
    public void remove(ChannelHandlerContext ctx){
        String qq = ctxToQQ.get(ctx);
        ctxMap.put(qq, ctx);
        ctxToQQ.put(ctx, qq);
    }
    public ChannelHandlerContext getCtx(String qq){
        return ctxMap.get(qq);
    }
    public String getQQ(ChannelHandlerContext ctx){
        return ctxToQQ.get(ctx);
    }
}
